use Entity;
use Managers;
use Controllers;
use Curses;
use DependencyResolver;
use Component;

package ResourceManager;

@ISA = qw/DependencyResolver Component/;

our $inject = sub{
    ($what, $where, $name) = (shift, shift, shift);
    $name = ref $what unless(defined($name));
    $where->{$name} = $what;
};


sub new{
    my $class = shift;

    my $self = {};
    bless $self, $class;

    $self->init();

    return $self;
}

sub init{
    my $self = shift;
    my @dependencies;

    $self->{COMPONENTS} = {};    

    $self->{COMPONENTS}->{LOGPATH} = 'castlerogue.log';
    $self->{COMPONENTS}->{LOGENABLE} = 1;
    $self->{COMPONENTS}->{"LogManager"} = LogManager->new();

    $self->{COMPONENTS}->{"MapManager"}     = MapManager    ->new();
    $self->{COMPONENTS}->{"EntityManager"}  = EntityManager ->new();
    $self->{COMPONENTS}->{"DisplayManager"} = DisplayManager->new();
    $self->{COMPONENTS}->{"ActionManager"}  = ActionManager ->new();
    $self->{COMPONENTS}->{"KeyboardController"} = KeyboardController->new();
    $self->{COMPONENTS}->{"InputManager"} = InputManager->new();
    $self->{COMPONENTS}->{"OperationManager"} = OperationManager->new();

    $self->{COMPONENTS}->{"DependencyResolver"} = $self; # who else?

# --------------------------------------------------------------------

    $self->resolveDependencies($self->getComponent("LogManager"));
    $self->{COMPONENTS}->{"LogManager"}->start;

    $self->resolveDependencies($self->getComponent("MapManager"));
    $self->resolveDependencies($self->getComponent("EntityManager"));
    $self->resolveDependencies($self->getComponent("DisplayManager"));
    $self->resolveDependencies($self->getComponent("ActionManager"));
    $self->resolveDependencies($self->getComponent("KeyboardController"));
    $self->resolveDependencies($self->getComponent("InputManager"));
    $self->resolveDependencies($self->getComponent("OperationManager"));
} # init

sub resolveDependencies{
    my $self = shift;
    my $obj = shift;
    my $dependenciesRef = $obj->dependencies;

    my @dependencies = @{$dependenciesRef};
      
#    $self->getComponent("LogManager")->log("----------  ".(ref $obj));

    foreach  $componentName (@dependencies){
	my $component;
	if ($componentName eq "ResourceManager"){
	    $component = $self;
	}else{
	    $component = $self->getComponent($componentName);
	}

#	$self->getComponent("LogManager")->log("*)".$obj." ".$component." ".(ref $component)." ".$componentName);


	&$inject($component, $obj, $componentName);
    }

}


sub getComponent{
    my $self = shift;
    my $componentName = shift;

    return $self->{COMPONENTS}->{$componentName};
}


sub disposeComponents{
    my $self = shift;

    my $display = $self->getComponent("DisplayManager");
    $display->dispose;

    my $log = $self->{COMPONENTS}->{"LogManager"};
    $log->end;
    
}
1;
